<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-07 15:46:30
 * @LastEditTime: 2024-02-28 20:17:22
 * @FilePath: \env-manager-pc\src\views\assets\warehouse\edit.vue
-->
<script setup lang="ts">
import { ElOption } from 'element-plus'
import type { FormInstance } from 'element-plus'
import type { VxeTableEvents } from 'vxe-table'
import dayjs from 'dayjs'
import { rules, useInitForm } from './page'
import { useOwnerOrgs } from '@/utils/dataHook'
import { ModelType } from '@/types/common'
import type { ModelOpen } from '@/types/page'
import assetsApi from '@/api/modules/assets'
import useUserStore from '@/store/modules/user'
import type { orderInfo } from '@/api/modules/types/assets'
import { QueryObj } from '@/utils/dataHook/data'

const emits = defineEmits(['submit'])
const dialogVisible = ref(false)
const { formData, initForm } = useInitForm()
const userStore = useUserStore()

const OwnerList = useOwnerOrgs()

const formRef = ref<FormInstance>()
const btnLoading = ref(false)
const modelType = ref(ModelType.add)
const tableData = ref([])
const tempRowData = ref<orderInfo>({} as orderInfo)
function handleClose() {
  close()
}

const InWarehouseTime = ref('')

function open(options: ModelOpen) {
  modelType.value = options.type
  if (options.data) {
    InWarehouseTime.value = dayjs().format('YYYY-MM-DD')
  }
  queryOrderList()
  dialogVisible.value = true
}

function doLoading(flag: boolean) {
  btnLoading.value = flag
}

async function getDeviceCodes(orderFormObjID: string) {
  const res = await assetsApi.GetOrderFormAssetCodes({ orderFormObjID })
  const rows: any = []
  Object.keys(res).forEach((key) => {
    const current = res[key]
    if (!current) {
      rows.push({ Name: key })
    }
  })
  tableData.value = rows
}

function submit() {
  formRef.value?.validate((vaild) => {
    if (vaild) {
      emits('submit', formData.value, doLoading)
    }
  })
}

function close() {
  dialogVisible.value = false
  btnLoading.value = false
  tableData.value = []
  initForm()
}
const tableRef = ref()
const selectChangeEvent: VxeTableEvents.CheckboxChange<any> = () => {
  const $table = tableRef.value
  if ($table) {
    const records = $table.getCheckboxRecords()
    formData.value.assetCodes = records.map((item: any) => item.Name)
  }
}

const loading = ref(false)
const orderList = ref<any>([])
async function queryOrderList() {
  try {
    const searchData = new QueryObj({
      objType: 'DIM.FilterCollection',
      Filters: [],
    })

    loading.value = true
    const res = await assetsApi.GetOrderForms({
      objFilter: searchData.getQuery(),
      objType: searchData.objType,
      pageSize: 100,
      pageNum: 1,
    })
    loading.value = false
    // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
    const { Objs } = res
    orderList.value = Objs || []
  }
  catch (e) {
    loading.value = false
  }
}

function chooseOrder(id: string) {
  if (!id) {
    return
  }
  const current = orderList.value.find((item: any) => item.ObjID === id)
  if (current) {
    tempRowData.value = current
  }
  getDeviceCodes(id)
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    append-to-body
    title="入库"
    width="80%"
    top="1%"
    draggable
    @closed="handleClose"
  >
    <div class="max-h-[65vh] w-full overflow-x-hidden overflow-y-auto">
      <ElForm ref="formRef" :model="formData" label-width="180px" label-position="top" label-suffix="：" :rules="rules">
        <ElRow :gutter="30">
          <ElCol :span="12">
            <ElFormItem label="订单号" prop="orderFormObjID">
              <ElSelect v-model="formData.orderFormObjID" :loading="loading" class="w-full" @change="chooseOrder">
                <ElOption v-for="item in orderList" :key="item.ObjID" :label="item.OrderFormCode" :value="item.ObjID" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="入库日期" prop="Name">
              <el-date-picker
                v-model="InWarehouseTime"
                class="w-full!"
                type="date"
                disabled
                placeholder="入库日期"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="产品名称" prop="AssetModelClassifyName">
              <ElInput v-model="tempRowData.AssetModelClassifyName" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="型号" prop="AssetModelName">
              <ElInput v-model="tempRowData.AssetModelName" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="资产状态" prop="StateName">
              <ElInput value="入库" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="入库地点" prop="ownerOrgObjID">
              <el-cascader
                v-model="formData.ownerOrgObjID" :options="OwnerList" class="w-full" :props="{ emitPath: false,
                                                                                               children: 'Children',
                                                                                               label: 'Name',
                                                                                               value: 'Code' }"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="入库人" prop="Location">
              <ElInput v-model="userStore.userInfo.Name" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="备注" prop="remark">
              <ElInput v-model="formData.remark" type="textarea" />
            </ElFormItem>
          </ElCol>
        </elrow>
        <ElFormItem label="" label-width="0" prop="assetCodes">
          <div class="w-full">
            <vxe-table
              ref="tableRef"
              height="500"
              :data="tableData"
              sync-resize border
              :row-config="{ isCurrent: true }"
              @checkbox-change="selectChangeEvent"
              @checkbox-all="selectChangeEvent"
            >
              <vxe-column type="checkbox" width="60" />
              <VxeColumn type="seq" title="序号" width="150" />
              <VxeColumn field="Name" title="设备编码" />
            </vxe-table>
          </div>
        </ElFormItem>
      </ElForm>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
